<script setup lang="ts">
import { ref, reactive } from 'vue'
import {
  Form as AForm,
  Input as AInput,
  Button as AButton,
  Checkbox as ACheckbox,
  message,
} from 'ant-design-vue'
import { useRouter } from 'vue-router'
import type { FormInstance } from 'ant-design-vue'
import { login } from '@/api/user'
import { useUserStore } from '@/stores/user'
import { CopyOutlined } from '@ant-design/icons-vue'
const formRef = ref<FormInstance>()
const router = useRouter()
const loading = ref(false)
const rememberMe = ref(false)
const userStore = useUserStore()

interface LoginForm {
  userAccount: string
  userPassword: string
}

const formState = reactive<LoginForm>({
  userAccount: '',
  userPassword: '',
})

const handleSubmit = async () => {
  try {
    loading.value = true
    await formRef.value?.validate()

    const response = await login({
      userAccount: formState.userAccount,
      userPassword: formState.userPassword,
    })

    if (response.status === 200 && response.data.code === 200) {
      const { token, ...userInfo } = response.data.data
      userStore.setToken(token)
      userStore.setUserInfo(userInfo)

      message.success('登录成功')
      router.push('/')
    } else {
      message.error('账号或密码错误')
    }
  } catch (error) {
    console.error('登录异常:', error)
  } finally {
    loading.value = false
  }
}

const copyText = (text: string) => {
  // 降级方案函数
  const fallbackCopyText = (text: string) => {
    const textArea = document.createElement('textarea');
    textArea.value = text;
    textArea.style.position = 'fixed';
    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();

    try {
      const successful = document.execCommand('copy');
      if (successful) {
        message.success('复制成功');
      } else {
        message.error('复制失败：浏览器不支持');
      }
    } catch (err) {
      console.error('降级复制失败:', err);
      message.error('复制失败');
    } finally {
      document.body.removeChild(textArea);
    }
  };

  // 主逻辑
  if (navigator.clipboard && navigator.clipboard.writeText) {
    navigator.clipboard.writeText(text)
      .then(() => {
        message.success('复制成功');
      })
      .catch(err => {
        console.error('复制失败:', err);
        // API失败时使用降级方案
        fallbackCopyText(text);
      });
  } else {
    // 浏览器不支持Clipboard API时使用降级方案
    fallbackCopyText(text);
  }
}
</script>

<template>
  <div id="login-page">
    <div class="login-container">
      <div class="login-box">
        <h2>系统登录</h2>
        <a-form
          :model="formState"
          :rules="{
            userAccount: [{ required: true, message: '请输入用户名/手机号/邮箱', trigger: 'blur' }],
            userPassword: [
              { required: true, message: '请输入密码', trigger: 'blur' },
              { min: 6, message: '密码长度不能小于6位', trigger: 'blur' },
            ],
          }"
          ref="formRef"
          @finish="handleSubmit"
          layout="vertical"
        >
          <a-form-item name="userAccount" label="用户名">
            <a-input
              v-model:value="formState.userAccount"
              placeholder="请输入用户名/手机号/邮箱"
              size="large"
            />
          </a-form-item>
          <a-form-item name="userPassword" label="密码">
            <a-input-password
              v-model:value="formState.userPassword"
              placeholder="请输入密码"
              size="large"
            />
          </a-form-item>
          <a-form-item>
            <div class="login-options">
              <a-checkbox v-model:checked="rememberMe">记住我</a-checkbox>
              <router-link to="/forgot-password">忘记密码？</router-link>
            </div>
          </a-form-item>
          <a-form-item>
            <a-button type="primary" html-type="submit" :loading="loading" size="large" block>
              登录
            </a-button>
          </a-form-item>
          <div class="register-link">
            还没有账号？
            <router-link to="/register">立即注册</router-link>
          </div>
        </a-form>
      </div>
    </div>
    <div class="login-footer">
      <h3 class="footer-title">
        尊敬的用户您好，欢迎登录智能树岛后台管理系统测试平台，下面将提供一个管理员账号和密码，祝您使用愉快
      </h3>
      <div class="credentials-container">
        <div class="credential-item">
          <span class="credential-label">管理员账号：</span>
          <span class="credential-text">admin</span>
          <a-button type="link" class="copy-btn" @click="copyText('admin')">
            <template #icon><CopyOutlined /></template>
          </a-button>
        </div>
        <div class="credential-item">
          <span class="credential-label">管理员密码：</span>
          <span class="credential-text">Admin123</span>
          <a-button type="link" class="copy-btn" @click="copyText('Admin123')">
            <template #icon><CopyOutlined /></template>
          </a-button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
#login-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 2rem;
}

.login-container {
  width: 100%;
  max-width: 1200px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 2rem;
}

.login-box {
  width: 100%;
  max-width: 420px;
  padding: 2.5rem;
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  transition: all 0.3s ease;
}

.login-box:hover {
  transform: translateY(-5px);
  box-shadow: 0 12px 28px rgba(0, 0, 0, 0.15);
}

h2 {
  text-align: center;
  margin-bottom: 2rem;
  color: #1890ff;
  font-size: 1.8rem;
  font-weight: 600;
  position: relative;
  padding-bottom: 0.8rem;
}

h2::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 60px;
  height: 3px;
  background: #1890ff;
  border-radius: 3px;
}

.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.register-link {
  text-align: center;
  margin-top: 1.5rem;
  color: #666;
}

.register-link a {
  color: #1890ff;
  font-weight: 500;
  margin-left: 0.5rem;
  transition: color 0.3s;
}

.register-link a:hover {
  color: #40a9ff;
  text-decoration: underline;
}

:deep(.ant-form-item-label) {
  padding-bottom: 6px;
}

:deep(.ant-input),
:deep(.ant-input-affix-wrapper) {
  padding: 10px 12px;
  border-radius: 6px;
  transition: all 0.3s;
}

:deep(.ant-input:focus),
:deep(.ant-input-affix-wrapper:focus),
:deep(.ant-input-affix-wrapper-focused) {
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

:deep(.ant-btn) {
  height: 44px;
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.3s;
}

:deep(.ant-btn-primary) {
  background: #1890ff;
}

:deep(.ant-btn-primary:hover) {
  background: #40a9ff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.4);
}

.login-footer {
  width: 100%;
  max-width: 800px;
  background: white;
  padding: 1.5rem;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  margin-top: 2rem;
  text-align: center;
}

.footer-title {
  font-size: 0.9rem;
  line-height: 1.5;
  color: #666;
  margin-bottom: 1.5rem;
}

.credentials-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 1rem;
}

.credential-item {
  display: flex;
  align-items: center;
  justify-content: center;
}

.credential-label {
  color: #1890ff;
  font-weight: 500;
}

.credential-text {
  color: #f5222d;
  font-weight: 600;
  margin: 0 4px;
}

.copy-btn {
  padding: 0 4px;
  font-size: 16px;
  color: #1890ff;
  transition: all 0.3s;
}

.copy-btn:hover {
  color: #40a9ff;
  transform: scale(1.1);
}

@media (max-width: 768px) {
  .login-box {
    padding: 1.5rem;
  }

  .login-footer {
    padding: 1rem;
  }
}
</style>
